package com.yungu.swift.order.helper.chain;

import com.yungu.swift.order.dao.OrderMapper;
import com.yungu.swift.order.helper.model.AssignScoreParam;
import com.yungu.swift.order.helper.model.DriverPrevOrderDiffVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 司机上一单完成时间处理器
 *
 * @author : cuixiuyin
 * @date : 2019/7/8
 */
@Slf4j
public class DriverPreviousOrderHandler extends AssignScoreHandler {

    private OrderMapper orderMapper;

    public DriverPreviousOrderHandler(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    @Override
    public void calculation(List<AssignScoreParam> scoreParams) {
        if (CollectionUtils.isNotEmpty(scoreParams)) {
            List<String> driverUuids = scoreParams.stream().map(AssignScoreParam::getDriverUuid).collect(Collectors.toList());
            // 得到上一单订单完成时间的时间间隔
            List<DriverPrevOrderDiffVo> diffVos = orderMapper.listPreviousOrderDiff(driverUuids);
            Map<String, Long> dissVoMap = diffVos.stream().collect(Collectors.toMap(DriverPrevOrderDiffVo::getDriverUuid,
                    DriverPrevOrderDiffVo::getDiff, (oldValue, newValue) -> newValue));
            scoreParams.forEach(scoreParam -> {
                Long diff = dissVoMap.get(scoreParam.getDriverUuid());
                scoreParam.setScore(scoreParam.getScore() + score(diff));
            });
        }
        if (nextHandler != null) {
            nextHandler.calculation(scoreParams);
        }
    }


    /**
     * 司机上一单完成时间分值计算
     * f(x)= 1-e^(-x^2/7200)
     *
     * @param diff 司机距离上一单的完成时间，单位：分钟
     * @return
     */
    public Double score(Long diff) {
        if (diff == null) {
            return 0.0;
        }
        double temp = 1 - Math.exp(Math.pow(diff, 2) / 7200 * -1);
        return BigDecimal.valueOf(temp).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
}
